package com.heatup.apt.management.controller;

import com.heatup.apt.common.constants.DataDictConstants;
import com.heatup.apt.common.constants.CourseConstants.CourseType;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.JsonUtils;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.management.service.DataDictService;
import com.heatup.apt.management.service.accessdevice.AccessDeviceService;
import com.heatup.apt.management.service.coach.CoachService;
import com.heatup.apt.management.service.course.CourseService;
import com.heatup.apt.management.service.course.CourseStandardService;
import com.heatup.apt.management.service.course.CourseTeamService;
import com.heatup.apt.management.service.store.StoreService;
import com.heatup.apt.model.AccessDevice;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.course.CourseTeamResultModel;
import com.heatup.apt.model.management.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by b3st9u on 16/9/30.
 */
@Controller
@RequestMapping("system/course")
public class CourseTeamController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CourseTeamController.class);
	@Autowired
	CourseService courseService;
	@Autowired
	CoachService coachService;
	@Autowired
	StoreService storeService;
	@Autowired
	CourseStandardService courseStandardService;
	@Autowired
	DataDictService dataDictService;
	@Autowired
	CourseTeamService courseTeamService;
	@Autowired
	private AccessDeviceService accessDeviceService;

	public static final String announcements = "请保管好个人贵重物品，以防丢失，本店概不负责";

	/**
	 * 团课列表页
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "to_course_team")
	public ModelAndView toCourseTeam(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		Map<String, Object> map = courseService.queryCourseTeamToList();
		model.addAllObjects(map);
		model.setViewName("course/course-team-list");
		return model;
	}

	/**
	 * 查询团课列表页
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "to_course_team_query")
	public ModelAndView toCourseTeamQuery(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		int page = RequestTools.RequestInt(request, "page", 0);
		int size = RequestTools.RequestInt(request, "size", 10);
		String date = RequestTools.RequestString(request, "daterange", "");
		int coachId = RequestTools.RequestInt(request, "coachId", 0);
		int storeId = RequestTools.RequestInt(request, "storeId", 0);
		int courseId = RequestTools.RequestInt(request, "courseId", 0);
		String status = RequestTools.RequestString(request, "status", "0");
		String isVipUsed = RequestTools.RequestString(request, "isVipUsed", "-1");
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("pageIndex", page);
		paramsMap.put("pageSize", size);
		if (coachId > 0)
			paramsMap.put("coachId", coachId);
		if (storeId > 0)
			paramsMap.put("storeId", storeId);
		if (courseId > 0) {
			paramsMap.put("courseId", courseId);
		}
		if ("0".equals(status)) {
			paramsMap.put("status", null);
		} else {
			paramsMap.put("status", status);
		}
		if (date.length() > 0) {
			String[] dates = date.split("~");
			if (dates.length > 1) {
				paramsMap.put("startDate", dates[0]);
				paramsMap.put("endDate", dates[1]);
			}
		}
		if("-1".equals(isVipUsed)){
			paramsMap.put("isVipUsed", null);
		}else{
			paramsMap.put("isVipUsed", isVipUsed);
		}
		
		Map<String, Object> objectMap = courseService.queryCourseTeamList(paramsMap);
		objectMap.put("coachId", coachId);
		objectMap.put("storeId", storeId);
		objectMap.put("courseId", courseId);
		objectMap.put("status", status);
		objectMap.put("daterange", date);
		objectMap.put("isVipUsed", isVipUsed);
		model.addAllObjects(objectMap);
		model.setViewName("course/course-team-list");
		return model;
	}

	/**
	 * 跳转到团课新增页面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "to_course_team_add")
	public ModelAndView toCourseTeamAdd(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		model.addObject("coachList", coachService.queryAllCoachInfo());
		model.addObject("storeList", storeService.queryStoreListWithWorkoutRoom());
		model.addObject("dataDictList",
				JsonUtils.obj2Json(dataDictService.queryDataDicts(DataDictConstants.DICT_TYPE_COURSE_ATTR)));
		model.addObject("courseStandards", courseStandardService.queryAllCourseStandard());
		model.addObject("isSuccess", false);
		model.setViewName("course/course-team-add");
		return model;
	}

	/**
	 * 团课 保存
	 *
	 * @param courseTeamResultModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "to_course_team_save", method = { RequestMethod.GET, RequestMethod.POST })
	public String courseTeamAdd(CourseTeamResultModel courseTeamResultModel) {
		String msg="success";
		if (courseTeamResultModel == null) {
			msg= "false";
		}
		
		SysUser user = this.getUserInfo();
		int userId = user.getId();
		courseTeamResultModel.setStatus("2");
		courseTeamResultModel.setCoachCount(1);
		courseTeamResultModel.setCourseType(CourseType.team_course.getType());
		int isVipUsed = courseTeamResultModel.getIsVipUsed()==null?0:courseTeamResultModel.getIsVipUsed();
		courseTeamResultModel.setIsVipUsed(isVipUsed);
		// 增加课程订单数量的判断
		if (courseTeamResultModel.getId() != null) {
			courseTeamResultModel.setUpdatedBy(userId);
			courseTeamResultModel.setUpdatedTime(new Date());
			int i = courseService.queryCourseOrderByCourseId(courseTeamResultModel.getId());
			if (i > 0) {
				CourseTeamResultModel courseTeamResultModelOld = courseTeamService
						.findCourseTeamResultModelById(courseTeamResultModel.getId());
				if (courseTeamResultModelOld != null) {
					BigDecimal price = courseTeamResultModel.getServicePrice().getPrice()==null?BigDecimal.valueOf(0L):courseTeamResultModel.getServicePrice().getPrice();
					BigDecimal oldPrice = courseTeamResultModelOld.getPrice()==null?BigDecimal.valueOf(0L):courseTeamResultModelOld.getPrice();
					// 判断已关联订单的课程信息是否有修改时间和价格
					if (!courseTeamResultModelOld.getStartDate().substring(0, 10).equals(courseTeamResultModel.getStartDate())
							|| !courseTeamResultModelOld.getStartTime().equals(courseTeamResultModel.getStartTime())
							|| !courseTeamResultModelOld.getEndTime().equals(courseTeamResultModel.getEndTime())
							|| courseTeamResultModel.getServicePrice().getPrimePrice().compareTo(courseTeamResultModelOld.getPrimePrice())!=0
							|| price.compareTo(oldPrice)!=0) {
						return "该团课已存在预定的订单，不能修改价格数据和时间等信息.";
					}
					
					/**
					 * 1. 如果当前报名人数 >= 课程最大人数， 则只能增，加能减
					 * 2. 如果 课程最大人数有变化，则触发排队的订单是否要变成正常订单
					 */
					if(courseTeamResultModelOld.getMaxCount().intValue()<=courseTeamResultModelOld.getCurrentCount().intValue()){
						//如果修改的课程最大人数小于之前的最大数
						if(courseTeamResultModel.getMaxCount().intValue()<courseTeamResultModelOld.getMaxCount().intValue()){
							return "该团课当前人数已报满，只能增加课程的最大人数值。";
						}
					}else{
						if ((courseTeamResultModelOld.getMaxCount().intValue() - courseTeamResultModel.getMaxCount()
								.intValue()) > (courseTeamResultModelOld.getMaxCount().intValue()
										- courseTeamResultModelOld.getCurrentCount().intValue())) {
							return "该课程已有订单关联，过度减少最大人数会导致出现排队异常。";
						}
					}
					
				}
			}
		}else{
			courseTeamResultModel.setCreatedBy(userId);
			courseTeamResultModel.setCreatedTime(new Date());
		}
		
		if (courseTeamService.saveCourseTeamInfo(courseTeamResultModel)) {
			msg= "success";
		}else{
			msg= "false";
		}
	
		return msg;
	}

	/**
	 * 打开编辑团课信息
	 * 
	 *
	 * @return
	 */
	@RequestMapping(value = "to_course_team_edit")
	public ModelAndView courseTeamEdit(HttpServletRequest request,@RequestParam("courseId") int courseId) {
		int conditionPage = RequestTools.RequestInt(request, "conditionPage", 0);
		String conditionDaterange = RequestTools.RequestString(request, "conditionDaterange", "");
		int conditionCoachId = RequestTools.RequestInt(request, "conditionCoachId", 0);
		int conditionStoreId = RequestTools.RequestInt(request, "conditionStoreId", 0);
		int conditionCourseId = RequestTools.RequestInt(request, "conditionCourseId", 0);
		String conditionStatus = RequestTools.RequestString(request, "conditionStatus", "0");
		String conditionIsVipUsed = RequestTools.RequestString(request, "conditionIsVipUsed", "-1");
		
		Map<String,Object> conditionMap= new HashMap<String,Object>();
		conditionMap.put("conditionPage", conditionPage);
		conditionMap.put("conditionDaterange", conditionDaterange);
		conditionMap.put("conditionCoachId", conditionCoachId);
		conditionMap.put("conditionStoreId", conditionStoreId);
		conditionMap.put("conditionCourseId", conditionCourseId);
		conditionMap.put("conditionStatus", conditionStatus);
		conditionMap.put("conditionIsVipUsed", conditionIsVipUsed);
		
		ModelAndView model = new ModelAndView("course/course-team-edit");
		model.addObject("coachList", coachService.queryAllCoachInfo());
		model.addObject("storeList", storeService.queryStoreListWithWorkoutRoom());
		model.addObject("courseStandards", courseStandardService.queryAllCourseStandard());
		model.addObject("dataDictList",JsonUtils.obj2Json(dataDictService.queryDataDicts(DataDictConstants.DICT_TYPE_COURSE_ATTR)));
		CourseTeamResultModel courseTeamResultModel = courseTeamService.findCourseTeamResultModelById(courseId);
		model.addObject("course", courseTeamResultModel);
		model.addObject("courseJson", JsonUtils.obj2Json(courseTeamResultModel));
		model.addObject("condition",conditionMap);

		return model;
	}

	/**
	 * 删除删除团课信息 删除逻辑：
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/to_course_team_delete")
	public String deleteCourseTeamById(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
		SysUser users = getUserInfo();
		String callback = RequestTools.RequestString(request, "callback", null);
		String courseId = (String) RequestTools.RequestString(request, "courseId", "0");
		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("courseId", courseId);
		mapWhere.put("userId", users.getId() + "");
		int bool = courseService.updateCourseInfoToDel(mapWhere);
		if (bool == 1) {
			apiResultModel.setData("删除成功！");
			apiResultModel.setLogined(true);
			apiResultModel.setMsg("删除成功");
			apiResultModel.setRet(bool);
		} else {
			apiResultModel.setData("删除失败！");
			apiResultModel.setLogined(true);
			apiResultModel.setMsg("删除失败");
			apiResultModel.setRet(bool);
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 在点击所属类别的时候 自动带出下面的所有信息
	 * 
	 * @param request
	 * @param httpServletResponse
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/get_course_resources")
	public String getCourseResources(HttpServletRequest request, HttpServletResponse httpServletResponse) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String standardId = RequestTools.RequestString(request, "standardCourse", null);
		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("standardId", standardId);
		Map<String, Object> mapData = courseService.getCourseResources(mapWhere);
		apiResultModel.setData(mapData);
		apiResultModel.setLogined(true);
		apiResultModel.setMsg("获取基本课程库信息");
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 查询对应门店 ID 的所有在线状态的门禁设备
	 *
	 * @param storeId 门店 ID
	 * @return 对应门店 ID 的所有在线状态的门禁设备
	 */
	@RequestMapping(value = "/storeAccessList")
	@ResponseBody
	public String accessStoreWorkoutRoomList(@RequestParam Integer storeId){
		List<AccessDevice> accessDeviceList = accessDeviceService.queryAccessStoreWorkoutRoomList(storeId);
		return JsonUtils.toJsonStrWithDateFormat(accessDeviceList);
	}
}